/* @author Stone at GDOU
   @date May 2020
*/
#include "DataFrame.h"

    

/* @brief Reset the DataFrame to initalized state, but do not clear the buffer
 */
static void DF_Reset(DataFrame *df) {
    df->escape = false;
    df->received = 0;
}


/* @brief Init a DataFrame struct
*/
void DF_Init(DataFrame *df, uint8_t buffer[], uint16_t buf_size, uint16_t frame_size)
{
    df->buf = buffer;
    df->buf_size = buf_size;
    df->frame_size = frame_size;
    df->received = 0;
    df->escape = false;
}


/* @brief Feed one character to the DataFrame struct.
 * @return if the the whole data frame is received, return 
    DF_FULL, otherwise return ERR.
   @note 
        Escape scheme:
        初遇DF_HEAD, 视为帧头, 在这一帧接收满之前, 接下来出现的 DF_HEAD 均视为数据. 在接收完一帧长度的数据后, 再出现 DF_HEAD 就被认为是帧头.
 */
status_t DF_Feed(DataFrame *df, int ch) {
    if (!df->escape && DF_HEAD == ch) {
        df->escape = true;
        return RECV_START;
    }
    if (df->received >= df->buf_size) {
        return ERR_OVERFLOW;
    }
    
    (df->buf)[df->received] = (uint8_t) ch;
    (df->received)++;
    
    if (df->received == df->frame_size) {
        DF_Reset(df);
        return RECV_DONE;
    }
    return RECEIVING;
}


